import React, { createContext, ReactElement } from 'react';

import { State, Action, Context } from './types';
import actions, { getAddress } from './actions';
import Provider from '../../components/Provider';

export const initialState: State = {
  isFetchFailed: false,
  receiverName: '',
  receiverMobilePhone: '',
  detail: '',
  districtInfo: []
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    case 'SET_RECEIVER_NAME':
      return { ...state, receiverName: action.value };
    case 'SET_RECEIVER_PHONE':
      return { ...state, receiverMobilePhone: action.value };
    case 'SET_DETAIL_ADDRESS':
      return { ...state, detail: action.value };
    case 'SET_DISTRICT_INFO':
      return { ...state, districtInfo: action.value };
    case 'INIT_INFO':
      return { ...state, ...action.value };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      reload={getAddress}
      {...props}
    />
  );
};
